#include "File.h"

File::File() : length_(0)
{

}

File::~File()
{
    close();
}

bool File::openForRead(const std::string &f)
{
    //1.
    close();

    //2.
    fr_.open(f, std::ios::binary);
    if (fr_.is_open())
    {
        fr_.seekg(0, std::ios::end);
        length_ = fr_.tellg();
        fr_.seekg(0, std::ios::beg);
        return true;
    }

    return false;
}

bool File::openForWrite(const std::string &f)
{
    //1.
    close();

    //2.
    fw_.open(f, std::ios::binary);
    return fw_.is_open();
}

std::size_t File::getLength()
{
    return length_;
}

void File::close()
{
    length_ = 0;
    if (fr_.is_open())
    {
        fr_.close();
    }
    else if (fw_.is_open())
    {
        fw_.close();
    }
}

void File::flush()
{
    fw_.flush();
}

void File::writeChars(const char * c, uint32_t n)
{
    fw_.write(c, n);
}

void File::readChars(char *c, uint32_t n)
{
    fr_.read(c, n);
}

void File::writeString(const std::string &s)
{
    if (s.empty())
    {
        write<uint32_t>(0);
    }
    else
    {
        write<uint32_t>(s.size());
        fw_.write(s.data(), s.size());
    }
}

std::string File::readString()
{
    uint32_t n = read<uint32_t>();
    if (n)
    {
        std::string s;
        s.resize(n);
        fr_.read(s.data(), n);
        return s;
    }
    else
    {
        return "";
    }
}